package com.yuneec.fly.fragments;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.os.SystemClock;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMapException;
import com.amap.api.maps.MapView;
import com.amap.api.maps.MapsInitializer;
import com.amap.api.maps.offlinemap.OfflineMapCity;
import com.amap.api.maps.offlinemap.OfflineMapManager;
import com.amap.api.maps.offlinemap.OfflineMapProvince;
import com.amap.api.maps.offlinemap.OfflineMapStatus;
import com.yuneec.fly.R;
import com.yuneec.fly.views.AmapOfflineChild;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jw.gu on 2016/7/13.
 */
public class DownloadOfflineMapFragment extends BaseFragment implements OfflineMapManager.OfflineMapDownloadListener, View.OnClickListener, ViewPager.OnPageChangeListener {
    private Context context;
    private OfflineMapManager amapManager = null;// 离线地图下载控制器
    private List<OfflineMapProvince> provinceList = new ArrayList<OfflineMapProvince>();// 保存一级目录的省直辖市
    private View leftUnderLine;
    private View rightUnderLine;

    // view pager 两个list以及他们的adapter
    private ViewPager viewPager;
    private ExpandableListView allCityLV;
    private ListView downloadedCityLV;

    private AllCityAdapter allCityAdapter;
    private DownloadedCityAdapter downloadedCityAdapter;
    private PagerAdapter mPageAdapter;

    private MapView mapView;

    /**
     * 更新所有列表
     */
    private final static int UPDATE_LIST = 0;

    @SuppressLint("HandlerLeak")
    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UPDATE_LIST:
                    if (viewPager.getCurrentItem() == 0) {
                        ((BaseExpandableListAdapter) allCityAdapter).notifyDataSetChanged();
                    } else {
                        downloadedCityAdapter.notifyDataChange();
                    }

                    break;
                default:
                    break;
            }
        }

    };

    @Override
    protected int getContentViewResourceId() {
        return R.layout.download_offline_map;
    }

    @Override
    public void init(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        context = getActivity();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        MapsInitializer.sdcardDir = new File(Environment.getExternalStorageDirectory(), "map").toString();
                    } else {
                        MapsInitializer.sdcardDir = new File(Environment.getRootDirectory(), "map").toString();
                    }
                    MapsInitializer.initialize(context);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                // 此版本限制，使用离线地图，请初始化一个MapView
                mapView = new MapView(context);

                initAllCityList();

                // 顶部
                leftUnderLine = selfView.findViewById(R.id.leftUnderLine);
                rightUnderLine = selfView.findViewById(R.id.rightUnderLine);
                selfView.findViewById(R.id.allCityTV).setOnClickListener(DownloadOfflineMapFragment.this);
                selfView.findViewById(R.id.downloadedCityTV).setOnClickListener(DownloadOfflineMapFragment.this);

                // view pager 用到了所有城市list和已下载城市list所有放在最后初始化
                viewPager = (ViewPager) selfView.findViewById(R.id.viewPager);

                mPageAdapter = new OfflinePagerAdapter();

                viewPager.setAdapter(mPageAdapter);
                viewPager.setCurrentItem(0);
                viewPager.setOnPageChangeListener(DownloadOfflineMapFragment.this);
            }
        }, 200);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mapView != null) {
            mapView.onDestroy();
        }
        try {
            if (amapManager != null) {
                amapManager.destroy();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 初始化所有城市列表
     */
    public void initAllCityList() {
        // 扩展列表
        allCityLV = new ExpandableListView(context);
        allCityLV.setDividerHeight(0);
        downloadedCityLV = new ListView(context);
        provinceList.clear();
        amapManager = new OfflineMapManager(context, DownloadOfflineMapFragment.this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                initProvinceListAndCityMap();
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        allCityAdapter = new AllCityAdapter();
                        // 为列表绑定数据源
                        allCityLV.setAdapter(allCityAdapter);
                        // adapter实现了扩展列表的展开与合并监听
                        allCityLV.setOnGroupCollapseListener(allCityAdapter);
                        allCityLV.setOnGroupExpandListener(allCityAdapter);
                        allCityLV.setGroupIndicator(null);
                        initDownloadedList();
                        selfView.findViewById(R.id.loadingLayout).setVisibility(View.GONE);
                    }
                });
            }
        }).start();
    }

    private void initProvinceListAndCityMap() {
        List<OfflineMapProvince> lists = amapManager.getOfflineMapProvinceList();
        provinceList.add(null);
        provinceList.add(null);
        provinceList.add(null);
        // 添加3个null 以防后面添加出现 index out of bounds

        ArrayList<OfflineMapCity> cityList = new ArrayList<OfflineMapCity>();// 以市格式保存直辖市、港澳、全国概要图
        ArrayList<OfflineMapCity> gangaoList = new ArrayList<OfflineMapCity>();// 保存港澳城市
        ArrayList<OfflineMapCity> gaiyaotuList = new ArrayList<OfflineMapCity>();// 保存概要图

        for (int i = 0; i < lists.size(); i++) {
            OfflineMapProvince province = lists.get(i);
            if (province.getCityList().size() != 1) {
                // 普通省份
                provinceList.add(i + 3, province);
                // cityMap.put(i + 3, cities);
            } else {
                String name = province.getProvinceName();
                if (name.contains("香港")) {
                    gangaoList.addAll(province.getCityList());
                } else if (name.contains("澳门")) {
                    gangaoList.addAll(province.getCityList());
                } else if (name.contains("全国概要图")) {
                    gaiyaotuList.addAll(province.getCityList());
                } else {
                    // 直辖市
                    cityList.addAll(province.getCityList());
                }
            }
        }

        // 添加，概要图，直辖市，港口
        OfflineMapProvince gaiyaotu = new OfflineMapProvince();
        gaiyaotu.setProvinceName("概要图");
        gaiyaotu.setCityList(gaiyaotuList);
        provinceList.set(0, gaiyaotu);// 使用set替换掉刚开始的null

        OfflineMapProvince zhixiashi = new OfflineMapProvince();
        zhixiashi.setProvinceName("直辖市");
        zhixiashi.setCityList(cityList);
        provinceList.set(1, zhixiashi);

        OfflineMapProvince gaogao = new OfflineMapProvince();
        gaogao.setProvinceName("港澳");
        gaogao.setCityList(gangaoList);
        provinceList.set(2, gaogao);
    }

    /**
     * 初始化已下载列表
     */
    public void initDownloadedList() {
        downloadedCityAdapter = new DownloadedCityAdapter();
        downloadedCityLV.setAdapter(downloadedCityAdapter);
    }

    /**
     * 离线地图下载回调方法
     */
    @Override
    public void onDownload(int status, int completeCode, String downName) {

        switch (status) {
            case OfflineMapStatus.EXCEPTION_NETWORK_LOADING:
                Toast.makeText(context, "网络异常", Toast.LENGTH_SHORT).show();
                amapManager.pause();
                break;
            default:
                break;
        }
        handler.sendEmptyMessage(UPDATE_LIST);
    }

    @Override
    public void onCheckUpdate(boolean hasNew, String name) {
        try {
            if (hasNew) {
                this.amapManager.remove(name);
                SystemClock.sleep(100);
                this.amapManager.downloadByCityName(name);
                Toast.makeText(context, "发现更新，正在下载新版离线地图", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "已是最新版", Toast.LENGTH_SHORT).show();
            }
        } catch (AMapException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onRemove(boolean success, String name, String describe) {
        handler.sendEmptyMessage(UPDATE_LIST);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.allCityTV) {
            viewPager.setCurrentItem(0);
            leftUnderLine.setVisibility(View.VISIBLE);
            rightUnderLine.setVisibility(View.INVISIBLE);
            downloadedCityAdapter.notifyDataChange();
        } else if (v.getId() == R.id.downloadedCityTV) {
            viewPager.setCurrentItem(1);
            leftUnderLine.setVisibility(View.INVISIBLE);
            rightUnderLine.setVisibility(View.VISIBLE);
            downloadedCityAdapter.notifyDataChange();
        }
    }

    @Override
    public void onPageScrollStateChanged(int arg0) {
    }

    @Override
    public void onPageScrolled(int arg0, float arg1, int arg2) {
    }

    @Override
    public void onPageSelected(int arg0) {
        switch (arg0) {
            case 0:
                leftUnderLine.setVisibility(View.VISIBLE);
                rightUnderLine.setVisibility(View.INVISIBLE);
                break;
            case 1:
                leftUnderLine.setVisibility(View.INVISIBLE);
                rightUnderLine.setVisibility(View.VISIBLE);
                break;
        }
        handler.sendEmptyMessage(UPDATE_LIST);
    }

    /**
     * 所有城市列表
     */
    public final class AllCityAdapter extends BaseExpandableListAdapter implements ExpandableListView.OnGroupCollapseListener, ExpandableListView.OnGroupExpandListener {
        private boolean[] isOpen;// 记录一级目录是否打开

        public AllCityAdapter() {
            isOpen = new boolean[provinceList.size()];
        }

        @Override
        public int getGroupCount() {
            return provinceList.size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            return provinceList.get(groupPosition).getProvinceName();
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            if (isNormalProvinceGroup(groupPosition)) {
                // 普通省份的第一个位置放省份
                try {
                    return provinceList.get(groupPosition).getCityList().size() + 1;
                } catch (Exception e) {
                    e.printStackTrace();
                    return 0;
                }
            }
            return provinceList.get(groupPosition).getCityList().size();
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            return null;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent) {
            TextView groupText;
            ImageView groupImage;
            if (convertView == null) {
                convertView = (RelativeLayout) RelativeLayout.inflate(context, R.layout.amap_offline_group, null);
            }
            groupText = (TextView) convertView.findViewById(R.id.groupText);
            groupImage = (ImageView) convertView
                    .findViewById(R.id.groupImage);
            try {
                groupText.setText(provinceList.get(groupPosition)
                        .getProvinceName());
                if (isOpen[groupPosition]) {
                    groupImage.setImageResource(R.drawable.ic_arrow_down);
                } else {
                    groupImage.setImageResource(R.drawable.ic_arrow_right);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return convertView;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView != null) {
                viewHolder = (ViewHolder) convertView.getTag();
            } else {
                viewHolder = new ViewHolder();
                AmapOfflineChild offLineChild = new AmapOfflineChild(context, amapManager);
                convertView = offLineChild.getOffLineChildView();
                viewHolder.mOfflineChild = offLineChild;
                convertView.setTag(viewHolder);
            }
            OfflineMapCity mapCity = null;
            viewHolder.mOfflineChild.setProvince(false);
            if (isNormalProvinceGroup(groupPosition)) {
                if (isProvinceItem(groupPosition, childPosition)) {
                    // 如果是省份，为了方便，进行一下处理
                    mapCity = getCicy(provinceList.get(groupPosition));
                    viewHolder.mOfflineChild.setProvince(true);
                } else {
                    // 减1处理，第一个被放置了省份
                    mapCity = provinceList.get(groupPosition).getCityList().get(childPosition - 1);
                }
            } else {
                mapCity = provinceList.get(groupPosition).getCityList().get(childPosition);
            }
            viewHolder.mOfflineChild.setOffLineCity(mapCity);
            return convertView;
        }


        private boolean isProvinceItem(int groupPosition, int childPosition) {
            // 不是特殊省份，而且子栏目中第一栏
            return isNormalProvinceGroup(groupPosition) && childPosition == 0;
        }

        /**
         * 是否为普通省份
         * 不是直辖市，概要图，港澳
         *
         * @param groupPosition
         * @return
         */
        private boolean isNormalProvinceGroup(int groupPosition) {
            return groupPosition > 2;
        }

        /**
         * 当选择子节点的时候，调用该方法
         */
        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }


        /**
         * 把一个省的对象转化为一个市的对象
         */
        public OfflineMapCity getCicy(OfflineMapProvince aMapProvince) {
            OfflineMapCity aMapCity = new OfflineMapCity();
            aMapCity.setCity(aMapProvince.getProvinceName());
            aMapCity.setSize(aMapProvince.getSize());
            aMapCity.setCompleteCode(aMapProvince.getcompleteCode());
            aMapCity.setState(aMapProvince.getState());
            aMapCity.setUrl(aMapProvince.getUrl());
            return aMapCity;
        }

        public final class ViewHolder {
            public AmapOfflineChild mOfflineChild;
        }

        public void onGroupCollapse(int groupPosition) {
            isOpen[groupPosition] = false;
        }

        @Override
        public void onGroupExpand(int groupPosition) {
            isOpen[groupPosition] = true;
        }
    }

    /**
     * 维护已经下载和下载过程中的列表
     */
    public final class DownloadedCityAdapter extends BaseAdapter {
        private List<OfflineMapCity> cities;
        private AmapOfflineChild currentOfflineChild;

        public DownloadedCityAdapter() {
            initCityList();
        }

        /**
         * 重新初始化数据加载数据
         */
        public void notifyDataChange() {
            initCityList();
        }

        private void initCityList() {
            if (cities != null) {
                cities.clear();
//				for (Iterator<OfflineMapCity> it = cities.iterator(); it.hasNext();) {
//					it.remove();
//				}
            } else {
                cities = new ArrayList<OfflineMapCity>();
            }
            cities.addAll(amapManager.getDownloadOfflineMapCityList());
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return cities.size();
        }

        @Override
        public Object getItem(int index) {
            return cities.get(index);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView != null) {
                viewHolder = (ViewHolder) convertView.getTag();
            } else {
                viewHolder = new ViewHolder();
                currentOfflineChild = new AmapOfflineChild(context, amapManager);
                convertView = currentOfflineChild.getOffLineChildView();
                viewHolder.mOfflineChild = currentOfflineChild;
                convertView.setTag(viewHolder);
            }
            viewHolder.mOfflineChild.setOffLineCity((OfflineMapCity) getItem(position));
            return convertView;
        }

        private final class ViewHolder {
            public AmapOfflineChild mOfflineChild;
        }
    }

    private final class OfflinePagerAdapter extends PagerAdapter {
        @Override
        public void destroyItem(View arg0, int arg1, Object arg2) {
            if (arg1 == 0) {
                viewPager.removeView(allCityLV);
            } else {
                viewPager.removeView(downloadedCityLV);
            }
        }

        @Override
        public void finishUpdate(View arg0) {
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public Object instantiateItem(View arg0, int arg1) {
            if (arg1 == 0) {
                viewPager.addView(allCityLV);
                return allCityLV;
            } else {
                viewPager.addView(downloadedCityLV);
                return downloadedCityLV;
            }
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == (arg1);
        }

        @Override
        public void restoreState(Parcelable arg0, ClassLoader arg1) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public void startUpdate(View arg0) {
        }
    }
}
